package com.wangtao.stock.aspect;

import com.wangtao.stock.annotation.SwitchSource;
import com.wangtao.stock.threadlocal.DataSourceHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Slf4j
@Aspect
@Component
public class DataSourceAspect {

    @Pointcut("@annotation(com.wangtao.stock.annotation.SwitchSource)")
    public void pointCut() {
    }

    /**
     * 在方法执行之前切换到指定的数据源
     */
    @Before(value = "pointCut()")
    public void beforeOpt(JoinPoint joinPoint) {
        //因为是对注解进行切面，所以这边无需做过多判定，
        // 直接获取注解的值，进行环绕，将数据源设置成远方，
        // 然后结束后，清楚当前线程数据源
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        SwitchSource switchSource = method.getAnnotation(SwitchSource.class);
        log.info("[SwitchSource]:" + switchSource.value());
        DataSourceHolder.setDataSources(switchSource.value());
    }

    @After(value = "pointCut()")
    public void afterOpt() {
        DataSourceHolder.clearDataSource();
        log.info("[SwitchSource]{}", DataSourceHolder.getDataSource());
    }
}
